'''
@author: boss
@mail: brunifrancesco02@gmail.com
@year: 2014
'''

from django.shortcuts import render,redirect
from django.http import HttpResponse, HttpResponseRedirect
import urllib,json,string,random
import logging,datetime
from google.appengine.ext import db
from google.appengine.api import mail
import facebook
from google.appengine.api import urlfetch
import logging
from decorators import auth_check,auth_check_is_admin
from models import User,Match
from forms import MatchForm
from google.appengine.api import memcache
import pickle

APPSECRET = "3870551a3f5ffd81f060a27aa6d45c36"
APPID ="125230024343613"

def addMatch(request):
	form = MatchForm(request.POST)
	if form.is_valid():
		user = User.get(request.session["pbusr"])
		m = Match(user=user,description =form.cleaned_data["description"],reward=form.cleaned_data["reward"])
		m.put()
		mts = Match.all().fetch(None).append(m)
		logging.info(len(mts))
		memcache.set("matches",mts)
		#memcache.add("matches",m)
		return HttpResponseRedirect("/secure/")
	else:
		logging.info("Not valid")
		return HttpResponseRedirect("/secure")

def showUsers(request):
	users = User.all()
	if (users is not None):
		logging.info(users.get())
	else:
		logging.info("aaaaaaaaaa")
	return render(request,"users.html",{'users':users})

def setCurrentUserAdmin(request):
	request.session["pbusradmn"] = request.session["pbusr"]
	del request.session["pbusr"]
	return HttpResponseRedirect("/")

def index(request):
	if 'pbusr' not in request.session:
		return HttpResponse("Questo e' l'index pubblico")
	else:
		user = User.get(request.session["pbusr"])
		if not (user is None):
			if(user.isAdmin == True):
					msg = "Ciao %s Sei l'admin" %user.name
					return HttpResponse(msg)
		return HttpResponse("Non sei l'admin; dovresti vedere ora le partite")
	

@auth_check_is_admin
def secure(request): 
	model={}
	user = User.get(request.session["pbusr"])
	#matches = Match.all().filter("user = ",user)
	if (user.facebookFanPageId is not None and not user.facebookFanPageId == ""):
		model["fanPageName"] = user.facebookFanPageName
		model["form"] = MatchForm()
		model["matches"] = memcache.get("matches")		
	else:
		graph = facebook.GraphAPI(user.accessToken)
		profile = graph.get_object("me/accounts")
		logging.info(profile["data"])
		model["data"] = profile["data"]
	return render(request,"secure.html",model)

def setFanPage(request):
	if(request.method == "POST"): 
		user = User.get(request.session["pbusr"])
		u = user
		u.facebookFanPageName = request.POST["facebookFanPageName"]
		u.accessTokenFanPage = request.POST["accessTokenFanPage"]
		u.facebookFanPageId = int(request.POST["facebookFanPageId"])
 		u.save()
		return HttpResponseRedirect("/secure")
	else:
		return HttpResponseRedirect("/")	

@auth_check
def logout(request):
	if 'pbusradmn' in request.session:
		del request.session["pbusradmn"]
	if 'isAdmin' in request.session:
		del request.session["isAdmin"]
	if 'pbusr' in request.session:
		del request.session["pbusr"]
	return HttpResponseRedirect("/")


def login(request):
	return HttpResponse("Non sei loggato; copia e incolla il link sotto per loggarti. Se vieni da '/secure' sarai considerato gestore della pizzeria. <br /><br /><br /> https://www.facebook.com/dialog/oauth?client_id=125230024343613&scope=publish_actions,manage_pages&redirect_uri=http://testapp.com:8080/callback")


def callback(request):
	try:
		code = request.GET["code"]
		url = '''https://graph.facebook.com/oauth/access_token?client_id=125230024343613&redirect_uri=http://testapp.com:8080/callback&client_secret=3870551a3f5ffd81f060a27aa6d45c36&code='''+code
		result = urlfetch.fetch(url)
		access_token = result.content.split("&")[0].split("=")[1]
		graph = facebook.GraphAPI(access_token)
		profile = graph.get_object("me")
		user = User.all().filter('facebookId =', int(profile["id"]))
		if(user.get() is None):
			logging.info("User is none from facebook")
			user = User(facebookId =int(profile["id"]),name = profile["name"],accessToken = access_token,fanPageName = "None",accessTokenFanPage = "None",isAdmin = False)
			key=user.put();
			request.session["pbusr"]=key
		else:
			logging.info("User is not none")
			if(user.get().isAdmin == True):
				logging.info(request.session["pbusr"])
				return HttpResponseRedirect("/secure")
                        request.session["pbusr"] = user.get().key()
		return HttpResponseRedirect("/") 
	except Exception,e:
		return HttpResponse(e)
